'use client';

import useToast from '@/hooks/useToast';
import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import type { IDifference, INginxKey } from '@/interfaces';
import { useMutation } from '@tanstack/react-query';
import { updateNginxKey } from '@/services/api';
import diff from 'microdiff';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';
import { useRouter } from 'next/navigation';
import { getDiffData } from '@/lib/tool';

export default function UpdateNginxConfigKeyPage({
  source,
  translatedFields,
}: {
  source: INginxKey;
  translatedFields: PrefixedTTranslatedFields<'logAdminPage'>;
}) {
  const initForm = {
    newSecret: false,
    remark: source.remark ?? '',
    used: source.used ?? false,
  };
  const { show } = useToast();
  const [form, setForm] = useState<
    Partial<INginxKey> & { newSecret?: boolean }
  >(initForm);
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);
  const router = useRouter();

  const updateNginxKeyMutation = useMutation(updateNginxKey);

  useEffect(() => {
    const diffData = diff(initForm, form);
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const id = source.id;
      const data = getDiffData(differenceData) as any;
      await updateNginxKeyMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.updateCompleted,
      });

      setTimeout(() => {
        show({
          type: 'PRIMARY',
          message: translatedFields.returning,
        });
      }, 1000);

      setTimeout(() => {
        router.back();
      }, 1500);
    } catch (e) {
      updateNginxKeyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'newSecret' || name === 'used') {
      setForm({
        ...form,
        [name]: value === 'true',
      });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">{translatedFields.logType}</label>
          <select
            name="newSecret"
            value={form.newSecret + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="newSecret"
          >
            {['true', 'false'].map((item) => {
              return (
                <option key={item} value={item}>
                  {item}
                </option>
              );
            })}
          </select>
        </div>

        <div>
          <label className="form-label">{translatedFields.remark}</label>
          <input
            className="form-control"
            name="remark"
            value={form.remark}
            onChange={onChangeForm}
            aria-describedby="remark"
          />
        </div>

        <div>
          <label className="form-label">{translatedFields.used}</label>
          <select
            name="used"
            value={form.used + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="used"
          >
            {['true', 'false'].map((item) => {
              return (
                <option key={item} value={item}>
                  {item}
                </option>
              );
            })}
          </select>
        </div>

        <button
          type="submit"
          disabled={updateNginxKeyMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateNginxKeyMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.update}
        </button>
      </form>
    </Box>
  );
}
